<script setup>
import {onMounted} from 'vue'
import {
  NAvatar,
  NButton,
  NFlex,
  NForm,
  NFormItem,
  NImage,
  NInput,
  NSelect,
  NTabPane,
  NTabs,
  NTag,
  useMessage
} from 'naive-ui'

import CommonPage from '@/components/page/CommonPage.vue'
import api from '@/api'
import default_image from "@/assets/images/mz.jpg";
import {getToken, renderIcon} from "@/utils";
import TheIcon from "@/components/icon/TheIcon.vue";
import {useCRUD} from "@/composables";
import CrudModal from "@/components/table/CrudModal.vue";
const base_path = import.meta.env.VITE_BASE
const message = useMessage()
const {
  modalVisible,
  modalAction,
  modalTitle,
  modalLoading,
  handleAdd,
  handleDelete,
  handleEdit,
  handleSave,
  modalForm,
  modalFormRef,
} = useCRUD({
  name: '咨询',
  initForm: {},
  doCreate: api.createFenzhen,
  doDelete: api.deleteFenzhen,
  doUpdate: api.updateFenzhen,
  refresh: () => on_ref(),
})

const props = defineProps({
  infoData: {
    type: Object,
    required: true
  }
});
const data = reactive({
    visit:[],
    card_loading:false,
    select_customer:{
    name:"未选择",
    card_number:"--",
    user_level_name:"--",
    mobile:"--",
    bi_date:"--",
    sex:"--",
    hkqd:"--",
    age:"--",
    created_at:"--",
    last_come:"--",
    record_hobby:[],
    totals:{
    weimei:0,
    cdp:0,
    fujia:0,
    other:0,
    buy_money:0,
    cases:0,
    appoint_count:0,
    return_count:0,
    operation_count:0,
    face_count:0,
    test_count:0,
    having_customers:0,
    customers_level5:0

    }
    },
    uploadAction: base_path+'/system/base/userimg',
    token: getToken(),
    pay:false,
    pay_data:[],
    payForm: {
      id:0,
      order_id:0,
      pay_type:3,
      images:[],
      images_pc:[]
    },
    get_jf_data:[],
    fjq:[],
    timeRange: [
        new Date(new Date().setDate(new Date().getDate() - 15)).setHours(0, 0, 0, 0), // 前15天 00:00:00
        new Date(new Date().setDate(new Date().getDate() + 15)).setHours(23, 59, 59, 999)  // 后15天 23:59:59.999
    ],
});

onMounted(() => {
  data.select_customer = props.infoData
    api.getProjects().then((res) => {
     data.projects = res.data.list
  })
  on_ref()
})

function formatDate(timestamp) {
  const date = new Date(timestamp);
  // 添加时区偏移（单位：分钟）
  const offset = date.getTimezoneOffset() * 60000; // 转为毫秒
  const localTime = new Date(date.getTime() - offset);
  return localTime.toISOString().replace('T', ' ').substring(0, 19);
}

function on_ref(){
  get_fenzhen_list()
}

function get_fenzhen_list(){
  data.card_loading = true
  api.getFenzhenList({
    user_id:data.select_customer.user_id,
    start_time: formatDate(data.timeRange[0]), // 开始日00:00:00
    end_time: formatDate(data.timeRange[1]), // 结束日23:59:59
  }).then((res) => {
     data.visit = res.data
     data.card_loading = false
     data.loading = false
  })
}


function handleTimeChange() {
  if(data.timeRange && data.timeRange.length === 2) {
    get_fenzhen_list()
  }
}

function go_cancel(item){
  api.deleteFenzhen({
    id:item.id,
  }).then((res) => {
    message.success('作废成功')
    on_ref()
  })
}


function save_visit(){
  handleSave()
}

function del_visit(){
  handleDelete()
}


function add_visit(){
  handleAdd()
  modalForm.value.user_id = data.select_customer.user_id
  modalForm.value.address_id = 1 // 杭州店
  modalForm.value.type = 88
}



</script>
<template>
  <div class="container" style="height: calc(100vh - 106px);">
    <div class="search">
      <n-date-picker
        v-model:value="data.timeRange"
        type="daterange"
        clearable
        @update:value="handleTimeChange"
      />
    </div>
     <n-spin :show="data.card_loading" style="--n-opacity-spinning:0.1;height: calc(100vh - 225px);">
       <n-scrollbar v-if="data.visit.length>0" style="max-height: calc(100vh - 180px);padding:0 20px 20px 0px">
          <n-collapse  class="cards" accordion :trigger-areas="['main']" :default-expanded-names="data.visit[0].id">
        <n-collapse-item :name="item.id" v-for="item in data.visit" class="card" >
          <template #header>
              <n-h6 prefix="bar" type="info" style="margin: 0;font-size: 16px">
                <div style="display: flex">
                  <n-button type="info" dashed size="large">咨询日期:</n-button>
                  <n-button style="margin-left: 10px" type="" dashed size="large">{{item.created_at}}</n-button>
                </div>
              </n-h6>
            </template>

          <div class="project_list">
            <div style="display: flex;gap: 10px;flex-wrap: wrap; align-content: space-between;">

                <n-card size="small" style="width: 260px;" :bordered="false" hoverable content-style="padding: 0px;" :segmented="{content: true,footer: 'soft',}">
                  <template #header><n-h6 prefix="bar" style="margin: 0;font-size: 14px">咨询时间</n-h6></template>
                  <template #footer>
                    <div>
                      {{item.created_at}}
                    </div>
                  </template>
                </n-card>

                <n-card size="small" style="width: 260px;" :bordered="false" hoverable content-style="padding: 0px;" :segmented="{content: true,footer: 'soft',}">
                  <template #header><n-h6 prefix="bar" style="margin: 0;font-size: 14px">咨询备注</n-h6></template>
                  <template #footer>
                    <div>
                      {{item.remark}}
                    </div>
                  </template>
                </n-card>
            </div>
            <div style="margin-top: 10px">
              <n-popconfirm @positive-click="go_cancel(item)">
                <template #trigger>
                   <n-button  type="error" style="margin-right:10px">
                     <TheIcon icon="material-symbols:delete" :size="16" class="mr-5" />作废</n-button>
                </template>
                确定要作废该回访吗？
              </n-popconfirm>
            </div>
          </div>
        </n-collapse-item>
      </n-collapse>
      </n-scrollbar>
       <n-empty v-else description="暂无数据"  style="margin: 50px"></n-empty>
     </n-spin>
    <div class="add_cases">
      <NFlex style="align-items: center;" justify="end">
        <n-button type="primary" style="width: 100px;margin-right: 30px" @click="add_visit">
          <TheIcon icon="material-symbols:add" :size="16" class="mr-5" />
          添加
        </n-button>
      </NFlex>
    </div>
    <n-drawer v-model:show="modalVisible" width="400px">
      <n-drawer-content title="添加咨询" closable>
        <NForm
        ref="modalFormRef"
        label-placement="left"
        label-align="left"
        :label-width="80"
        :model="modalForm"
      >
          <NFormItem label="选择项目" path="project_id">
            <NSelect
              v-model:value="modalForm.project_id"
              :options="data.projects"
              placeholder="输入名称检索"
              filterable
              label-field="title"
              value-field="id"
              style="width: 100%"
              remote
              clearable
              multiple
            />
          </NFormItem>
          <NFormItem label="咨询时间" path="day">
            <n-date-picker
              v-model:formatted-value="modalForm.day"
              type="datetime"
              clearable
              placeholder="请输入咨询时间"
              style="width: 100%"
            />
          </NFormItem>
          <NFormItem label="咨询备注" path="remark">
            <n-input type="textarea" v-model:value="modalForm.remark" placeholder="请输入咨询备注"/>
          </NFormItem>
        </NForm>
         <template #footer>
        <n-button type="primary"  @click="save_visit">
          <TheIcon icon="material-symbols:save-sharp" :size="16" class="mr-5" />保存</n-button>
           <n-popconfirm @positive-click="del_visit" v-if="modalForm.id>0">
        <template #trigger>
          <n-button type="error"   style="margin-left:10px">
            <TheIcon icon="material-symbols:contract-delete" :size="16" class="mr-5"/>
            删除
          </n-button>
        </template>
        确定要删除吗？
      </n-popconfirm>
      </template>

      </n-drawer-content>


    </n-drawer>
  </div>



</template>


<style>
 .container{
   padding: 10px;
   position: relative;
   height:100%;
   .search{
     margin-bottom: 10px;
   }
 }
 .cards{
   margin:0px;
 }
 .project{margin-bottom: 10px;}
 .project_list{
   background: #f3f3f3;
   padding: 20px;
   border-radius: 5px;

 }
 .add_cases{
   height:60px;
   position: absolute;
   bottom: 0;
   background: #eee;
   width: 100%;
   padding: 10px;
   border-top-left-radius: 5px;
 }


</style>
<style scoped>

</style>